<template>
    <div>
        <div id="container"></div>
        <el-button type="primary" style="position: absolute; top: 50px; left: 150px; z-index: 9999;" @click="clickRuler"
            plain>
            {{ ceju }}
        </el-button>
        <el-button type="success" style="position: absolute; top: 50px; left: 250px; z-index: 9999;"
            @click="startBoxSelect" plain>
            {{ kuangxuan }}
        </el-button>
        <div style="position: absolute; top: 100px; left: 150px; z-index: 9999;" class="input-card"
            v-show="kuangxuan == '框选范围'">
            <div class="input-item">
                <input type="radio" name="func" value="rectangle" v-model="selectedTool" /><span
                    class="input-text">矩形</span>
                <input type="radio" name="func" value="circle" v-model="selectedTool" /><span
                    class="input-text">圆形</span>
                <input type="radio" name="func" value="polygon" v-model="selectedTool" /><span
                    class="input-text">多边形</span>
            </div>
        </div>
        <div style="position: absolute; top: 150px; left: 20px; z-index: 9999; width: 500px;" class="input-card"
            v-show="kuangXuanData.length > 0">
            <el-row :gutter="10">

                <el-col :xs="24" :sm="24" :md="6" :lg="6">
                    <el-table :data="kuangXuanData" height="300" width="50" @row-click="handleRowClick">
                        <el-table-column label="站点名称" align="center" prop="stationName" />
                        <!-- <el-table-column label="经度" align="center" prop="lon" /> -->
                        <!-- <el-table-column label="纬度" align="center" prop="lat" /> -->
                        <!-- <el-table-column label="海拔高度" align="center" prop="altitude" /> -->
                        <!-- <el-table-column label="具体地址" align="center" prop="address" /> -->
                        <!-- <el-table-column label="缓冲区范围" align="center" prop="bufferRange" /> -->
                        <!-- <el-table-column label="最新监测时间" align="center" prop="monitorTime" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.monitorTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
</el-table-column> -->
                    </el-table>
                </el-col>
                <el-col :xs="24" :sm="24" :md="18" :lg="18">
                    <!-- <el-row :gutter="5">
                        <el-col :span="8">
                            <el-select v-model="selectedTimeType" placeholder="请选择时间类型" @change="handleTimeTypeChange">
                                <el-option label="小时" value="hour"></el-option>
                                <el-option label="天" value="day"></el-option>
                                <el-option label="月" value="month"></el-option>
                                <el-option label="年" value="year"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="16">
                            <el-date-picker v-model="selectedTimeRange" :type="timePickerType" start-placeholder="开始时间"
                                end-placeholder="结束时间" range-separator="-" value-format="yyyy-MM-dd HH:mm:ss"
                                :picker-options="pickerOptions" @change="getChartData"></el-date-picker>
                        </el-col>
                    </el-row> -->
                    <custom-chart :data="chartData" :fields="['temperature', 'humidity', 'water', 'rain']"
                        :time-type="selectedTimeType" width="100%" height="325px" />
                </el-col>
            </el-row>

        </div>
    </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import CustomChart from './CustomChart.vue';
import { getAll } from "@/api/system/station";
import { searchData } from "@/api/system/data";

export default {
    name: "GaoDeMap",
    components: {
        CustomChart
    },
    mounted() {
        this.initAMap();
    },
    unmounted() {
        this.map?.destroy();
    },
    data() {
        return {
            map: null, // 用于存储地图实例
            ruler: null,
            mouseTool: null, // 鼠标工具
            boxSelectRectangle: null, // 框选矩形
            markers: [], // 存储所有 marker
            selectedTool: "rectangle", // 当前选择的绘制工具
            kuangxuan: '框选范围',
            ceju: '启动测距',
            kuangXuanData: [],
            searchDataParam: {
                stationId: null,
                timeType: null,
                params: {
                    beginTime: null,
                    endTime: null
                }
            },
            chartData: [],
            selectedStation: null,
            selectedTimeType: 'hour',
            selectedTimeRange: [],
            timePickerType: 'datetimerange',
            pickerOptions: {
                disabledDate(time) {
                    return false; // 默认不禁用任何日期
                }
            },
        };
    },
    methods: {
        clickRuler() {
            if (this.ceju == '启动测距') {
                this.ruler.turnOn();
                this.ceju = '取消测距'
            } else {
                this.ruler.turnOff();
                this.ceju = '启动测距'
            }

        },
        startBoxSelect() {
            if (this.mouseTool) {
                this.mouseTool.close(true); // 关闭之前的鼠标工具
                this.mouseTool = null;
                this.kuangxuan = '框选范围';
                this.boxSelectRectangle = null;
                this.kuangXuanData = [];
            } else {
                this.mouseTool = new AMap.MouseTool(this.map);
                this.mouseTool.on("draw", (e) => {
                    // 移除之前绘制的图形
                    if (this.boxSelectRectangle) {
                        this.map.remove(this.boxSelectRectangle);
                    }
                    this.boxSelectRectangle = e.obj;
                    this.handleBoxSelect();
                });
                this.draw(this.selectedTool);
                this.kuangxuan = '取消框选';
            }

        },
        handleBoxSelect() {
            const bounds = this.boxSelectRectangle.getBounds();
            const ne = bounds.getNorthEast(); // 东北角
            const sw = bounds.getSouthWest(); // 西南角
            console.log("框选范围：", ne, sw);
            this.getMarkersInBoxSelectRange(ne, sw);
        },
        getMarkersInBoxSelectRange(ne, sw) {
            this.kuangXuanData = [];
            const markersInBoxSelectRange = this.markers.filter((marker) => {
                const position = marker.getPosition();
                return (
                    position.lng >= sw.lng &&
                    position.lng <= ne.lng &&
                    position.lat >= sw.lat &&
                    position.lat <= ne.lat
                );
            });
            for (var i = 0; i < markersInBoxSelectRange.length; i++) {
                this.kuangXuanData.push(markersInBoxSelectRange[i].getExtData());
            }
            this.selectedStation = this.kuangXuanData[0].stationId;
            // 设置默认值
            if (this.kuangXuanData.length > 0) {
                this.selectedStation = this.kuangXuanData[0].stationId; // 默认选择第一个站点
            }
            this.selectedTimeType = 'hour'; // 默认选择小时
            this.setDefaultTimeRange(); // 设置默认时间范围

            this.getChartData();//获取图表数据
            console.log("框选范围内的 marker 信息：", this.kuangXuanData);
        },
        draw(type) {
            switch (type) {
                case "rectangle":
                    this.mouseTool.rectangle({
                        fillColor: "rgba(255, 255, 0, 0.5)", // 填充颜色
                        strokeColor: "red", // 边线颜色
                        strokeWeight: 2, // 边线宽度
                    });
                    break;
                case "circle":
                    this.mouseTool.circle({
                        fillColor: "rgba(255, 255, 0, 0.5)", // 填充颜色
                        strokeColor: "red", // 边线颜色
                        strokeWeight: 2, // 边线宽度
                    });
                    break;
                case "polygon":
                    this.mouseTool.polygon({
                        fillColor: "rgba(255, 255, 0, 0.5)", // 填充颜色
                        strokeColor: "red", // 边线颜色
                        strokeWeight: 2, // 边线宽度
                    });
                    break;
            }
        },
        initAMap() {
            window._AMapSecurityConfig = {
                securityJsCode: "1bf2b385f0c84322da5e2078076e5baa",
            };
            AMapLoader.load({
                key: "32318674389174577b90b86620722bfa", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [
                    "AMap.Scale",
                    "AMap.HawkEye",
                    "AMap.MapType",
                    "AMap.ControlBar",
                    "AMap.RangingTool",
                    "AMap.MouseTool",
                ], //需要使用的的插件列表
            })
                .then((AMap) => {
                    this.map = new AMap.Map("container", {
                        // 设置地图容器id
                        viewMode: "3D", // 是否为3D地图模式
                        mapStyle: "amap://styles/fresh", //设置地图的显示样式
                        zoom: 7, // 初始化地图级别
                        center: [104.06, 30.67], // 初始化地图中心点位置
                    });
                    var HawkEye = new AMap.HawkEye(); //缩放工具条实例化
                    this.map.addControl(HawkEye); //添加控件

                    var Scale = new AMap.Scale(); //缩放工具条实例化
                    this.map.addControl(Scale); //添加控件

                    var MapType = new AMap.MapType(); //缩放工具条实例化
                    this.map.addControl(MapType); //添加控件

                    var ControlBar = new AMap.ControlBar(); //缩放工具条实例化
                    this.map.addControl(ControlBar); //添加控件

                    this.ruler = new AMap.RangingTool(this.map); //缩放工具条实例化
                    this.showStataionPoint();
                })
                .catch((e) => {
                    console.log(e);
                });
        },
        showStataionPoint() {
            getAll().then((res) => {
                var stationList = res.data;
                for (var i = 0; i < stationList.length; i++) {
                    var station = stationList[i];
                    // 创建标记
                    var marker = new AMap.Marker({
                        position: new AMap.LngLat(station.lon, station.lat), // 标记的位置
                        title: station.stationName, // 鼠标悬停显示的标题
                        extData: station, // 自定义数据
                    });
                    this.markers.push(marker);

                    // 为标记添加点击事件
                    marker.on("click", (e) => {
                        this.clickPoint(e);
                    });

                    // 根据 station.bufferRange 绘制圆形
                    if (station.bufferRange) {
                        var circle = new AMap.Circle({
                            center: new AMap.LngLat(station.lon, station.lat), // 圆心位置
                            radius: station.bufferRange, // 半径，单位米
                            strokeColor: "red", // 边线颜色
                            strokeOpacity: 1, // 边线透明度
                            strokeWeight: 2, // 边线宽度
                            fillColor: "rgba(255, 0, 0, 0.5)", // 填充颜色（红色背景，50% 透明度）
                            fillOpacity: 0.5, // 填充透明度
                            zIndex: 50,
                        });
                        this.map.add(circle);
                    }
                }
                // 将标记添加到地图上
                this.map.add(this.markers);
            });
        },
        clickPoint(e) {
            // 获取标记的自定义数据
            const markerData = e.target.getExtData();

            // 创建信息窗体内容
            var infoContent = `
            <div class="info-window">
                <h3>${markerData.stationName}</h3>
                经度: ${markerData.lon}<br/>
                纬度: ${markerData.lat}<br/>
                地址：${markerData.address || '无'}<br/>
                监测时间: ${markerData.monitorTime || '无'}
            </div> `
            // 创建信息窗体
            var infoWindow = new AMap.InfoWindow({
                content: infoContent, // 信息窗体内容
                offset: new AMap.Pixel(0, -10), // 信息窗体偏移量
                autoMove: true, // 自动调整位置
                closeWhenClickMap: true, // 点击地图关闭窗体
            });

            // 打开信息窗体
            infoWindow.open(this.map, e.target.getPosition());
        },
        handleTimeTypeChange(value) {
            this.selectedTimeType = value;
            switch (value) {
                case 'hour':
                    this.timePickerType = 'datetimerange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
                    break;
                case 'day':
                    this.timePickerType = 'daterange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
                    break;
                case 'month':
                    this.timePickerType = 'monthrange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
                    break;
                case 'year':
                    this.timePickerType = 'daterange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        },
                        firstDayOfWeek: 1, // 设置每周的第一天为周一
                        shortcuts: [
                            {
                                text: '今年',
                                onClick(picker) {
                                    const start = new Date();
                                    start.setFullYear(start.getFullYear());
                                    start.setMonth(0);
                                    start.setDate(1);
                                    const end = new Date();
                                    end.setFullYear(end.getFullYear() + 1);
                                    end.setMonth(0);
                                    end.setDate(0);
                                    picker.$emit('pick', [start, end]);
                                }
                            },
                            {
                                text: '去年',
                                onClick(picker) {
                                    const start = new Date();
                                    start.setFullYear(start.getFullYear() - 1);
                                    start.setMonth(0);
                                    start.setDate(1);
                                    const end = new Date();
                                    end.setFullYear(end.getFullYear());
                                    end.setMonth(0);
                                    end.setDate(0);
                                    picker.$emit('pick', [start, end]);
                                }
                            }
                        ]
                    };
                    break;
                default:
                    this.timePickerType = 'datetimerange';
                    this.pickerOptions = {
                        disabledDate(time) {
                            return false; // 默认不禁用任何日期
                        }
                    };
            }
            this.getChartData();
        },
        getChartData() {
            this.searchDataParam.stationId = this.selectedStation;
            this.searchDataParam.timeType = this.selectedTimeType;
            if (null != this.selectedTimeRange && '' != this.selectedTimeRange) {
                this.searchDataParam.params["beginTime"] = this.selectedTimeRange[0];
                this.searchDataParam.params["endTime"] = this.selectedTimeRange[1];
            }

            searchData(this.searchDataParam).then((res) => {
                this.chartData = res.data;
            })
        },
        setDefaultTimeRange() {
            const now = new Date();
            const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0); // 今天零点
            const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), 0, 0); // 现在所在的小时

            // 格式化为 yyyy-MM-dd HH:mm:ss
            const formatTime = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            };

            this.selectedTimeRange = [formatTime(start), formatTime(end)];
        },
        handleRowClick(row, column, event) {
            this.selectedStation = row.stationId
            this.getChartData();
        },
    },
};
</script>
<style scoped>
#container {
    width: 100%;
    height: 800px;
}

.input-card {
    background-color: white;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.input-item {
    margin-bottom: 0px;
}

.input-text {
    margin-left: 5px;
}
</style>